import { createSlice } from "@reduxjs/toolkit";
import { Toast } from "antd-mobile";

export const PersonSlice = createSlice({
  name: "PersonSlice",
  initialState: {
    PersonList: [
      {
        id: 1,
        name: "娃哈哈",
        code: "411381199908206666",
        state: false,
      },
      {
        id: 2,
        name: "嘻嘻嘻",
        code: "311381198404158888",
        state: false,
      },
      {
        id: 3,
        name: "噗嗤噗嗤",
        code: "011381199507233321",
        state: false,
      },
    ],
  },
  reducers: {
    SwitchState(state, { payload }) {
      const item = state.PersonList.find((item) => item.id === payload.id);
      item.state = !item.state;
    },
    delPer(state, { payload }) {
      state.PersonList = state.PersonList.filter(
        (item) => item.id !== payload.id
      );
    },
    addPer(state, { payload }) {
      const item = state.PersonList.find((item) => item.id === payload.id);
      if (!item) {
        state.PersonList.push(payload);
        Toast.show("添加成功");
      } else {
        Toast.show("此人已存在");
      }
    },
    EditPer(state, { payload }) {
      const item = state.PersonList.find((item) => item.id === payload.id);
      if (item) {
        Object.assign(item, payload);
        Toast.show("修改成功");
      } else {
        Toast.show("修改失败，请检查是否已存在此人");
      }
    },
  },
});

export const { SwitchState, delPer, addPer, EditPer } = PersonSlice.actions;

export default PersonSlice.reducer;
